package com.newsproject.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import com.newsproject.mapper.SearchMapper;
import com.newsproject.pojo.Category;
import com.newsproject.pojo.HotSearch;
import com.newsproject.pojo.Post;
import com.newsproject.pojo.Tag;
import com.newsproject.pojo.User;
import com.newsproject.service.SearchService;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchMapper searchMapper;
    
    @Override
    public ArrayList<User> searchUsers(String username) {
        return searchMapper.searchUsers(username);
    }

    @Override
    public ArrayList<Post> searchNews(String title, int category) {
        return searchMapper.searchNews(title, category);
    }

    @Override
    public ArrayList<HotSearch> getHotSearches(int limit) {
        return searchMapper.getHotSearches(limit);
    }

    
    @Override
    public boolean checkCategoryIdOrTagId(int categoryId, int tagId) {
        Category category = searchMapper.hasCategory(categoryId);
        Tag tag = searchMapper.hasTag(tagId);
        boolean categoryExists = category != null;
        boolean tagExists = tag != null;
        return categoryExists && tagExists;
    }
    
    @Override
    public Post getPostById(int postId) {
        return searchMapper.getPostById(postId);
    }
    
    @Override
    public ArrayList<HotSearch> getTodayHotSearches(int limit, String today) {
        return searchMapper.getTodayHotSearches(limit, today);
    }
    
    // 搜索页面（json）
    @Transactional
    @Override
    public Map<String, Object> search(String query,HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        ArrayList<User> userList = new ArrayList<User>();
        ArrayList<Post> postList = new ArrayList<Post>();
        userList=searchUsers(query);
        postList=searchNews(query, -1);

        result.put("message", "搜索成功！");
        result.put("searchString", query);
        result.put("userList", userList);
        result.put("postList", postList);
        result.put("userInfo",session.getAttribute("userInfo"));
        return result;
    }

    // 搜索页面
    @Transactional
    @Override
    public ModelAndView searchPage(String searchString,HttpSession session) {
        ModelAndView response = new ModelAndView("search");

        // 处理搜索参数
        if (searchString == null || searchString.equals("")) {
            response.addObject("message", "请输入搜索内容！");
            response.addObject("userInfo",session.getAttribute("userInfo"));
            return response;
        }
        if (searchString.length() > 20) {
            response.addObject("message", "搜索内容过长！");
            response.addObject("userInfo",session.getAttribute("userInfo"));
            return response;
        }
        searchString = searchString.trim();

        // 检测分类和参数是否存在
        // if(checkCategoryIdOrTagId(category_id, tag_id) == false) {
        //     response.addObject("message", "分类ID或标签ID不存在！");
        //     return response;
        // }

        // 调用搜索服务
        ArrayList<User> userList = searchUsers(searchString);
        ArrayList<Post> postList = searchNews(searchString, -1);

        if (userList.isEmpty() && postList.isEmpty()) {
            response.addObject("searchString", searchString);
            response.addObject("message", "没有搜索到相关内容！");
            response.addObject("userInfo",session.getAttribute("userInfo"));
            return response;
        }

        response.addObject("searchString", searchString);
        response.addObject("userList", userList);
        response.addObject("postList", postList);
        response.addObject("userInfo",session.getAttribute("userInfo"));
        response.addObject("message", "搜索成功！");
        return response;
    }

    // 总热搜
    @Transactional
    @Override
    public ModelAndView hotSearch(int Num) {
        ModelAndView response = new ModelAndView("layout/mainPage");

        if(Num<=0) {
            response.addObject("message", "页数不能小于0！");
            return response;
        }
        //获取今天的时间
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        String formattedDate = dateFormat.format(today);
        response.addObject("date", formattedDate);
        ArrayList<HotSearch> hotSearchList = getHotSearches((Num-1)*10);
        // 获取新闻ID对应的新闻keyword
        ArrayList<Post> postLists = new ArrayList<>();
        ArrayList<String> keywords = new ArrayList<>();
        for(HotSearch hotSearch : hotSearchList) {
            int postId = hotSearch.getHotPostId();
            postLists.add(searchMapper.getPostById(postId));
            keywords.add(hotSearch.getKeyword());
        }
        if(postLists.size() == 0) {
            response.addObject("message", "热搜列表为空！");
            return response;
        }

        // 检测热搜列表是否为空
        if (hotSearchList.isEmpty()) {
            response.addObject("message", "热搜列表为空！");
            return response;
        }

        response.addObject("keywords", keywords);
        response.addObject("postLists", postLists);
        response.addObject("message", "获取热搜成功！");
        return response;
    }

    // 总热搜(json)
    @Transactional
    @Override
    public Map<String, Object>  HotSearch(int Num) {
        Map<String, Object> response = new HashMap<>();

        if(Num<=0) {
            response.put("message", "页数不能小于0！");
            return response;
        }
        //获取今天的时间
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        String formattedDate = dateFormat.format(today);
        response.put("date", formattedDate);
        ArrayList<HotSearch> hotSearchList = getHotSearches((Num-1)*10);
        // 获取新闻ID对应的新闻keyword
        ArrayList<Post> postLists = new ArrayList<>();
        ArrayList<String> keywords = new ArrayList<>();
        for(HotSearch hotSearch : hotSearchList) {
            int postId = hotSearch.getHotPostId();
            postLists.add(searchMapper.getPostById(postId));
            keywords.add(hotSearch.getKeyword());
        }
        if(postLists.size() == 0) {
            response.put("message", "热搜列表为空！");
            return response;
        }

        // 检测热搜列表是否为空
        if (hotSearchList.isEmpty()) {
            response.put("message", "热搜列表为空！");
            return response;
        }

        response.put("keywords", keywords);
        response.put("postLists", postLists);
        response.put("message", "获取热搜成功！");
        return response;
    }

    // 今日热搜
    @Transactional
    @Override
    public ModelAndView todayHotSearch(int Num) {
        ModelAndView response = new ModelAndView("layout/mainPage");

        if(Num<=0) {
            response.addObject("message", "页数不能小于0！");
            return response;
        }
        //获取今天的时间
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        String formattedDate = dateFormat.format(today);
        response.addObject("date", formattedDate);
        // 获取今天凌晨0点的时间戳
        long currentTimeMillis = System.currentTimeMillis();
        long todayStartTimeMillis = currentTimeMillis - (currentTimeMillis % (24 * 60 * 60 * 1000));
        String todayStartTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(todayStartTimeMillis));

        ArrayList<HotSearch> hotSearchList = getTodayHotSearches((Num-1)*5,todayStartTime);
        // 获取新闻ID对应的新闻keyword
        ArrayList<Post> postLists = new ArrayList<>();
        ArrayList<String> keywords = new ArrayList<>();
        for(HotSearch hotSearch : hotSearchList) {
            int postId = hotSearch.getHotPostId();
            postLists.add(searchMapper.getPostById(postId));
            keywords.add(hotSearch.getKeyword());
        }
        if(postLists.size() == 0) {
            response.addObject("message", "热搜列表为空！");
            return response;
        }

        // 检测热搜列表是否为空
        if (hotSearchList.isEmpty()) {
            response.addObject("message", "热搜列表为空！");
            return response;
        }

        response.addObject("keywords", keywords);
        response.addObject("postLists", postLists);
        response.addObject("message", "获取热搜成功！");
        return response;
    }

    // 今日热搜（json）
    @Transactional
    @Override
    public Map<String, Object> searchApi(int Num) {
        Map<String, Object> response = new HashMap<>();
        if(Num<=0) {
            response.put("message", "页数不能小于0！");
            return response;
        }
        //获取今天的时间
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        String formattedDate = dateFormat.format(today);
        response.put("date", formattedDate);
        // 获取今天凌晨0点的时间戳
        long currentTimeMillis = System.currentTimeMillis();
        long todayStartTimeMillis = currentTimeMillis - (currentTimeMillis % (24 * 60 * 60 * 1000));
        String todayStartTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(todayStartTimeMillis));

        ArrayList<HotSearch> hotSearchList = getTodayHotSearches((Num-1)*5,todayStartTime);
        // 获取新闻ID对应的新闻keyword
        ArrayList<Post> postLists = new ArrayList<>();
        ArrayList<String> keywords = new ArrayList<>();
        for(int i = 0; i < hotSearchList.size(); i++) {
            int postId = hotSearchList.get(i).getHotPostId();
            postLists.add(searchMapper.getPostById(postId));
            keywords.add(hotSearchList.get(i).getKeyword());
        }
        if(postLists.size() == 0) {
            response.put("message", "热搜列表为空！");
            return response;
        }

        // 检测热搜列表是否为空
        if (hotSearchList.isEmpty()) {
            response.put("message", "热搜列表为空！");
            return response;
        }
        response.put("keywords", keywords);
        response.put("postLists", postLists);
        response.put("message", "获取热搜成功！");
        return response;
    }

}
